package com.hm.service.framework.session;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.hm.service.framework.crypto.CBC.AES_CBC;
import com.hm.service.framework.crypto.KeyConstant;

import java.time.Duration;
import java.time.Instant;
import java.util.HashMap;

public class TokenUtils {
    //默认有效期是24小时
    public static final long SURVIVAL_TIME = 1000 * 60 * 60 * 24;

    //生成Token
    public static String generateToken(String userId) {
        TokenBean token = new TokenBean();
        token.setUserId(userId);
        token.setCreationTime(System.currentTimeMillis());
        String str = JSON.toJSONString(token);
        //采用CBC加密模式增加偏移量
        return AES_CBC.encrypt(KeyConstant.TokenSecretKey, KeyConstant.TokenIvParameter, str);
    }

    public static HashMap<String, String> verify(String token) {
        HashMap<String, String> resMap = new HashMap<>();
        try {
            if (token == null || token.isEmpty()) {
                resMap.put("state", "3");
                resMap.put("msg", "token为空");
                return resMap;
            }
            TokenBean tokenBean = decryptToken(token);
            //判断时间是否超时
            long creationTime = tokenBean.getCreationTime();
            long timeDifference = calculateTimeDifference(creationTime, System.currentTimeMillis());
            if (timeDifference > SURVIVAL_TIME) {
                //颁发时间到了
                resMap.put("state", "1");
                resMap.put("msg", "token过期了");
            } else {
                resMap.put("state", "0");
                resMap.put("msg", "验证通过");
            }
        } catch (Exception e) {
            resMap.put("state", "2");
            resMap.put("msg", "验证异常：" + e.getMessage());
        }
        return resMap;
    }

    public static TokenBean decryptToken(String token) {
        String decrypt = AES_CBC.decrypt(KeyConstant.TokenSecretKey, KeyConstant.TokenIvParameter, token);
        return JSONObject.parseObject(decrypt, TokenBean.class);
    }

    private static long calculateTimeDifference(long timestamp1, long timestamp2) {
        // 将时间戳转换为Instant对象
        Instant instant1 = Instant.ofEpochMilli(timestamp1);
        Instant instant2 = Instant.ofEpochMilli(timestamp2);
        // 计算时间差并返回结果（单位：毫秒）
        Duration duration = Duration.between(instant1, instant2);
        return duration.toMillis();
    }
}
